package com.ouyeel.cw.util;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.ouyeel.cw.model.FieldBean;
import com.ouyeel.cw.model.TableInfo;

import java.util.List;

/**
 * @author song xj
 * @version 1.0
 * @create 2020-06-29 13:57
 * @copyright
 **/
public class SqlUtils {

    public static List<FieldBean> getFieldsFromExcle(String path) {
        try {
            if (ObjectUtil.isNotEmpty(path)) {
                ExcelReader reader = ExcelUtil.getReader(path);
                List<FieldBean> all = reader.readAll(FieldBean.class);
                return all;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String buildSql(List<FieldBean> fields, TableInfo tableInfo) {
        if (ObjectUtil.isNotEmpty(fields)) {
            StringBuilder sb = new StringBuilder("CREATE TABLE `" + tableInfo.getTableName() + "` ( \n");
            fields.forEach(x -> {
                sb.append("\t");
                if (x.getFieldName().equals(tableInfo.getPk())) {
                    sb.append("`" + x.getFieldName() + "` int(11) NOT NULL AUTO_INCREMENT COMMENT '" + x.getComment() + "',\n");
                } else {
                    String notNull = " ";
                    if (x.isNotNull()) {
                        notNull = " NOT NULL";
                    }
                    String defalutValue = " ";
                    if (ObjectUtil.isNotEmpty(x.getDefaultValue())) {
                        if (x.getDefaultValue().equals("CURRENT_TIMESTAMP")) {
                            defalutValue = " DEFAULT " + x.getDefaultValue();
                        } else if (NumberUtil.isNumber(x.getDefaultValue())) {
                            defalutValue = " DEFAULT " + x.getDefaultValue();
                        } else {
                            defalutValue = " DEFAULT '" + x.getDefaultValue() + "'";
                        }
                    }
                    String comment = " ";
                    if (ObjectUtil.isNotEmpty(x.getComment())) {
                        comment = " COMMENT '" + x.getComment() + "'";
                    }
                    sb.append("`" + x.getFieldName() + "` ");
                    sb.append(x.getFiledType());
                    sb.append(notNull);
                    sb.append(defalutValue);
                    sb.append(comment);
                    sb.append(",\n");
                }
            });
            sb.append("\t");
            sb.append("PRIMARY KEY (`" + tableInfo.getPk() + "`) \n");
            sb.append(") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='" + tableInfo.getComment() + "';");
            return sb.toString();
        }

        return null;
    }
}
